package com.shirley.pers.zhufengfmvi.customViews;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.shirley.pers.zhufengfmvi.R;
import com.shirley.pers.zhufengfmvi.entities.FocusImageList;
import com.shirley.pers.zhufengfmvi.entities.FocusImageListInfo;
import com.shirley.pers.zhufengfmvi.tasks.DiscoveryRecommendTask;
import com.shirley.pers.zhufengfmvi.tasks.TaskCallback;
import com.shirley.pers.zhufengfmvi.tasks.TaskResult;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Description: 轮播图展示View<br/>
 * <p/>
 * Copyright (c) , 2016, Shirley Xian <br/>
 * This program is protected by copyright laws. <br/>
 * ClassName: CarouselImagesView<br/>
 * Date: 2016/4/7 17:50
 *
 * @author Shirley Xian
 * @version 1.0
 */
public class CarouselImagesView extends FrameLayout {

    private static final String TAG = CarouselImagesView.class.getSimpleName();
    //轮播图片缩影
    public static int itemIndex = 0;
    //轮播图片数目
    public static int imageCount = 0;
    //轮播时间间隔 秒值
    public static final int TIME_INTERVAL = 4;
    //轮播图片是否自动启动
    public static boolean isAutoPlay = true;
    //handle轮询标记
    private static final int CAROUSEL_TAG = 0;
    //需要轮播的图片
    private List<ImageView> mImageViews;
    //轮播图下方的黑点的集合
    private List<View> mDotViews;

    private ViewPager mViewPager;

    private ScheduledExecutorService scheduledExecutorService;

    public Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case CAROUSEL_TAG:
                    mViewPager.setCurrentItem(itemIndex, true);
                    break;
            }
            return true;
        }
    });

    public CarouselImagesView(Context context) {
        this(context, null);
    }

    public CarouselImagesView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CarouselImagesView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    /**
     * 开始轮播图切换
     */
    private void startPlay() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new CarouselTask(), 1, TIME_INTERVAL, TimeUnit.SECONDS);
    }

    /**
     * 停止轮播图切换
     */
    private void stopPlay() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
        }
    }

    private void init(final Context context) {

        LayoutInflater.from(context).inflate(R.layout.item_focus_image_discovery_recommend_list, this, true);

        mImageViews = new ArrayList<>();
        DiscoveryRecommendTask task = new DiscoveryRecommendTask(new TaskCallback() {
            @Override
            public void onTaskFinished(TaskResult result) {
                if (result != null) {
                    int state = result.state;
                    if (state == 0) {
                        Object data = result.data;
                        if (data != null) {
                            if (data instanceof JSONObject) {
                                JSONObject jsonObject = (JSONObject) data;
                                try {
                                    //获取头部焦点图片
                                    JSONObject jsonObj = jsonObject.getJSONObject("focusImages");
                                    FocusImageList focusImageList = new FocusImageList();
                                    focusImageList.parseJson(jsonObj);
                                    List<FocusImageListInfo> list = focusImageList.getList();
                                    for (FocusImageListInfo focusImageListInfo : list) {
                                        String ImageUrl = focusImageListInfo.getPic();
                                        ImageView iv = new ImageView(context);
                                        Picasso.with(context).load(ImageUrl).into(iv);
                                        iv.setScaleType(ImageView.ScaleType.FIT_XY);
                                        mImageViews.add(iv);
                                    }

                                    if (!mImageViews.isEmpty()) {
                                        imageCount = mImageViews.size();
                                        Log.i(TAG, "onTaskFinished: ===>header下载到的图片数有："+imageCount);

                                        View dotLayout = findViewById(R.id.item_focus_image_layout_dot_discovery_recommend_list);
                                        ViewGroup dotLayoutGroup = (ViewGroup) dotLayout;
                                        mDotViews = new ArrayList<>();
                                        for (int i = 0; i < imageCount; i++) {
                                            ImageView dotView = new ImageView(context);
                                            dotView.setBackgroundResource(R.drawable.dot_lightgray);
                                            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(40,40);
                                            dotView.setLayoutParams(layoutParams);
                                            dotLayoutGroup.addView(dotView);
                                            mDotViews.add(dotView);
                                        }

                                        mViewPager = (ViewPager) CarouselImagesView.this.findViewById(R.id.item_focus_image_viewpager_discovery_recommend_list);
                                        mViewPager.setFocusable(true);
                                        mViewPager.setAdapter(new MyViewPagerAdapter());
                                        mViewPager.addOnPageChangeListener(CarouselImagesView.this.new MyPageChangeListener());

                                        if (isAutoPlay) {
                                            startPlay();
                                        }
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else if (state == 8) {
                        Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
                    } else if (state == 9) {
                        //Snackbar.make(getView(), "服务器数据错误", Snackbar.LENGTH_SHORT).show();
                        Toast.makeText(context, "服务器数据错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        task.execute();
    }

    private class MyViewPagerAdapter extends PagerAdapter {

        /**
         * Return the number of views available.
         */
        @Override
        public int getCount() {
            int count = 0;
            if (mImageViews != null) {
                count = mImageViews.size();
            }
            return count;
        }

        /**
         * Determines whether a page View is associated with a specific key object
         * as returned by {@link #instantiateItem(ViewGroup, int)}. This method is
         * required for a PagerAdapter to function properly.
         *
         * @param view   Page View to check for association with <code>object</code>
         * @param object Object to check for association with <code>view</code>
         * @return true if <code>view</code> is associated with the key object <code>object</code>
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * Create the page for the given position.  The adapter is responsible
         * for adding the view to the container given here, although it only
         * must ensure this is done by the time it returns from
         * {@link #finishUpdate(ViewGroup)}.
         *
         * @param container The containing View in which the page will be shown.
         * @param position  The page position to be instantiated.
         * @return Returns an Object representing the new page.  This does not
         * need to be a View, but can be some other container of the page.
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mImageViews.get(position));
            return mImageViews.get(position);
        }

        /**
         * Remove a page for the given position.  The adapter is responsible
         * for removing the view from its container, although it only must ensure
         * this is done by the time it returns from {@link #finishUpdate(ViewGroup)}.
         *
         * @param container The containing View from which the page will be removed.
         * @param position  The page position to be removed.
         * @param object    The same object that was returned by
         *                  {@link #instantiateItem(View, int)}.
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mImageViews.get(position));
        }
    }

    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {
        boolean isAutoPlay = false;

        /**
         * This method will be invoked when the current page is scrolled, either as part
         * of a programmatically initiated smooth scroll or a user initiated touch scroll.
         *
         * @param position             Position index of the first page currently being displayed.
         *                             Page position+1 will be visible if positionOffset is nonzero.
         * @param positionOffset       Value from [0, 1) indicating the offset from the page at position.
         * @param positionOffsetPixels Value in pixels indicating the offset from position.
         */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        /**
         * This method will be invoked when a new page becomes selected. Animation is not
         * necessarily complete.
         *
         * @param position Position index of the new selected page.
         */
        @Override
        public void onPageSelected(int position) {
            Log.i(TAG, "onPageSelected: " + position);
            itemIndex = position;
            for (int i = 0; i < mDotViews.size(); i++) {
                if (itemIndex == i) {
                    mDotViews.get(i).setBackgroundResource(R.drawable.dot_black);
                } else {
                    mDotViews.get(i).setBackgroundResource(R.drawable.dot_lightgray);
                }
            }
        }

        /**
         * Called when the scroll state changes. Useful for discovering when the user
         * begins dragging, when the pager is automatically settling to the current page,
         * or when it is fully stopped/idle.
         *
         * @param state The new scroll state.
         * @see ViewPager#SCROLL_STATE_IDLE
         * @see ViewPager#SCROLL_STATE_DRAGGING
         * @see ViewPager#SCROLL_STATE_SETTLING
         */
        @Override
        public void onPageScrollStateChanged(int state) {
            Log.i(TAG, "onPageScrollStateChanged: state:" + state);
            switch (state) {
                case ViewPager.SCROLL_STATE_IDLE:
                    //滑动结束
//              Indicates that the pager is in an idle, settled state. The current page is fully in view and no animation is in progress.
                    if (mViewPager.getCurrentItem() == mViewPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        Log.i(TAG, "onPageScrollStateChanged: 0:");
                        mViewPager.setCurrentItem(0);
                    } else if (mViewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        mViewPager.setCurrentItem(mViewPager.getAdapter().getCount() - 1);
                        Log.i(TAG, "onPageScrollStateChanged: last:");
                    }
                    break;
                case ViewPager.SCROLL_STATE_DRAGGING:
                    //手势在滑动
                    //Indicates that the pager is currently being dragged by the user.
                    isAutoPlay = false;
                    break;
                case ViewPager.SCROLL_STATE_SETTLING:
                    //Indicates that the pager is in the process of settling to a final position.
                    //界面切换中
                    isAutoPlay = true;
                    break;
            }
        }
    }

    private class CarouselTask implements Runnable {
        /**
         * Starts executing the active part of the class' code. This method is
         * called when a thread is started that has been created with a class which
         * implements {@code Runnable}.
         */
        @Override
        public void run() {
            synchronized (mViewPager) {
                itemIndex = (itemIndex + 1) % mImageViews.size();
                mHandler.obtainMessage(CAROUSEL_TAG).sendToTarget();
            }
        }
    }
}
